<template>
  <view class="booking-page">
    <!-- 自定义导航栏 -->
    <custom-navbar
      :title="'预约参观'"
      :background-color="'#FFFFFF'"
    ></custom-navbar>

    <view class="container">
      <!-- 日期选择 -->
      <view class="section date-section">
        <view class="section-title">选择日期</view>
        <scroll-view class="date-scroll" scroll-x>
          <view
            v-for="(item, index) in dateList"
            :key="index"
            class="date-item"
            :class="{ active: selectedDate === index }"
            @click="selectDate(index)"
          >
            <text class="weekday">{{ item.weekday }}</text>
            <text class="date">{{ item.date }}</text>
          </view>
        </scroll-view>
      </view>

      <!-- 时间段选择 -->
      <view class="section time-section">
        <view class="section-title">选择时间段</view>
        <view class="time-grid">
          <view
            v-for="(item, index) in timeList"
            :key="index"
            class="time-item"
            :class="{ active: selectedTime === index, disabled: item.disabled }"
            @click="selectTime(index, item.disabled)"
          >
            <text class="time">{{ item.time }}</text>
            <text class="period">{{ item.period }}</text>
          </view>
        </view>
      </view>

      <!-- 人数选择 -->
      <view class="section count-section">
        <view class="section-title">选择人数</view>
        <view class="count-control">
          <view class="count-btn minus" @click="decreaseCount">
            <uni-icons type="down" size="20" color="#999"></uni-icons>
          </view>
          <input
            type="number"
            class="count-input"
            v-model="visitorCount"
            @blur="checkCountInput"
          />
          <view class="count-btn plus" @click="increaseCount">
            <uni-icons type="up" size="20" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 访客信息表单 -->
      <view class="section form-section">
        <view class="section-title">访客信息</view>
        <view class="form">
          <view class="form-item">
            <text class="form-label">姓名</text>
            <input
              class="form-input"
              type="text"
              v-model="formData.realname"
              placeholder="请输入姓名"
            />
          </view>
          <view class="form-item">
            <text class="form-label">手机号码</text>
            <input
              class="form-input"
              type="number"
              v-model.number="formData.phone"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </view>
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea
              class="form-textarea"
              placeholder="请输入备注信息（选填）"
            />
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view
        class="submit-btn"
        :class="{ disabled: !isFormValid }"
        @click="submitBooking"
      >
        确认预约
      </view>
    </view>

    <!-- 底部标签栏 -->
    <tab-bar :current="2"></tab-bar>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from "vue";
import CustomNavbar from "@/components/custom-navbar/index.vue";
import TabBar from "@/components/tab-bar/index.vue";
import { request } from "@/utils/request";

// 预约参观接口
const reqBook = (data) => {
	return request({
	  url: "/venues/booking",
	  method: "post",
	  data: JSON.stringify(data)
	})
}

// 日期选择
const dateList = ref([]);
const selectedDate = ref(0);

// 时间段选择
const timeList = ref([
  { time: "09:00-12:00", period: "上午", disabled: false },
  { time: "13:00-17:00", period: "下午", disabled: false },
]);
const selectedTime = ref(0);

// 人数选择
const visitorCount = ref(1);
const MIN_COUNT = 1;
const MAX_COUNT = 10;

// 表单数据
const formData = ref({
  userId: 0,
  realname: "",
  phone: undefined,
  bookTime: undefined
});

// 表单校验
const isFormValid = computed(() => {
  return (
    formData.value.realname.trim() !== "" && /^1\d{10}$/.test(formData.value.phone)
  );
});

// 生成未来7天的日期列表
const generateDateList = () => {
  const today = new Date();
  const list = [];

  for (let i = 0; i < 7; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);

    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekday =
      i === 0 ? "今天" : i === 1 ? "明天" : getWeekday(date.getDay());

    list.push({
      date: `${month}/${day}`,
      weekday,
      full: date,
    });
  }

  dateList.value = list;
};

// 获取星期几
const getWeekday = (day) => {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return weekdays[day];
};

// 选择日期
const selectDate = (index) => {
  selectedDate.value = index;

  // 模拟不同日期有不同的时间段可用状态
  if (index % 2 === 0) {
    timeList.value[2].disabled = true;
  } else {
    timeList.value[2].disabled = false;
  }

  // 如果选中了不可用的时间段，重置选择
  if (timeList.value[selectedTime.value].disabled) {
    selectedTime.value = 0;
  }
};

// 选择时间段
const selectTime = (index, disabled) => {
  if (disabled) return;
  selectedTime.value = index;
};

// 增加人数
const increaseCount = () => {
  if (visitorCount.value < MAX_COUNT) {
    visitorCount.value++;
  }
};

// 减少人数
const decreaseCount = () => {
  if (visitorCount.value > MIN_COUNT) {
    visitorCount.value--;
  }
};

// 检查人数输入
const checkCountInput = () => {
  // 将字符串转为数字
  let value = parseInt(visitorCount.value);

  // 检查是否是有效数字
  if (isNaN(value)) {
    visitorCount.value = MIN_COUNT;
    return;
  }

  // 限制范围
  if (value < MIN_COUNT) {
    visitorCount.value = MIN_COUNT;
	console.log(visitorCount.value)
  } else if (value > MAX_COUNT) {
    visitorCount.value = MAX_COUNT;
  }
};

// 提交预约
const submitBooking = async () => {
  if (!isFormValid.value) {
    uni.showToast({
      title: "请完善表单信息",
      icon: "none",
    });
    return;
  }

  formData.value.userId = uni.getStorageSync('userInfo').userId

  let bookTime = new Date(dateList.value[selectedDate.value].full)
  if (selectedTime.value == 0) {
	bookTime.setHours(9, 0, 0, 0)
  } else {
	bookTime.setHours(13, 0, 0, 0)
  }
  formData.value.bookTime = bookTime
  // count: visitorCount.value,

  console.log("预约信息：", formData.value);

  // 模拟提交请求
  uni.showLoading({
    title: "提交中...",
  });

  try {
	await reqBook(formData.value)
  } catch (err) {
	uni.showToast({
	  title: "请输入有效手机号",
	  icon: "error",
	});
	return
  } finally {
	uni.hideLoading();
  }

  uni.showToast({
    title: "预约成功",
    icon: "success",
  });
  
  uni.$emit('UpdateBooking', true);

  // 清空表单
  visitorCount.value = 1;
  formData.value = {
	userId: 0,
    realname: "",
    phone: undefined,
	bookTime: undefined
  };

    // 跳转到个人中心
    uni.switchTab({
      url: "/pages/profile/index",
    });
};

// 页面加载
onMounted(() => {
  generateDateList();
});

watch(() => visitorCount.value,
  () => {
    nextTick();
  })
</script>

<style lang="scss" scoped>
.booking-page {
  background-color: $uni-bg-color-grey;
  width: 100vw;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.container {
  max-width: 100vw;
  padding: $spacer-4;
  box-sizing: border-box;
}

// 通用section样式
.section {
  margin-bottom: $spacer-6;
  background-color: $uni-bg-color;
  border-radius: $uni-border-radius-lg;
  padding: $spacer-4;
  box-shadow: $box-shadow-card;

  .section-title {
    font-size: $uni-font-size-lg;
    font-weight: 500;
    margin-bottom: $spacer-4;
  }
}

// 日期选择样式
.date-scroll {
  white-space: nowrap;
  width: 100%;
}

.date-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120rpx;
  height: 120rpx;
  margin-right: $spacer-3;
  border: 1px solid $uni-border-color;
  border-radius: $uni-border-radius-base;
  transition: all 0.3s;

  &.active {
    background: $gradient-primary;
    border-color: transparent;

    .weekday,
    .date {
      color: $uni-text-color-inverse;
    }
  }

  .weekday {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
    margin-bottom: $spacer-1;
  }

  .date {
    font-size: $uni-font-size-base;
    font-weight: 500;
  }
}

// 时间段选择样式
.time-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: $spacer-3;
}

.time-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: $spacer-3;
  border: 1px solid $uni-border-color;
  border-radius: $uni-border-radius-base;
  transition: all 0.3s;

  &.active {
    background: $gradient-primary;
    border-color: transparent;

    .time,
    .period {
      color: $uni-text-color-inverse;
    }
  }

  &.disabled {
    opacity: 0.5;
    background-color: $uni-bg-color-hover;
    cursor: not-allowed;
  }

  .time {
    font-size: $uni-font-size-base;
    font-weight: 500;
    margin-bottom: $spacer-1;
  }

  .period {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
  }
}

// 人数选择样式
.count-control {
  display: flex;
  align-items: center;
  justify-content: center;
}

.count-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid $uni-border-color;
  border-radius: $uni-border-radius-sm;
}

.count-input {
  width: 120rpx;
  height: 80rpx;
  text-align: center;
  margin: 0 $spacer-3;
  border: 1px solid $uni-border-color;
  border-radius: $uni-border-radius-sm;
}

// 表单样式
.form-item {
  margin-bottom: $spacer-4;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: $uni-font-size-base;
  margin-bottom: $spacer-2;
}

.form-input,
.form-textarea {
  width: calc(100% - 2 * $spacer-3);
  padding: $spacer-3;
  border: 1px solid $uni-border-color;
  border-radius: $uni-border-radius-base;
  background-color: $uni-bg-color;
  font-size: $uni-font-size-base;
}

.form-textarea {
  height: 200rpx;
}

// 提交按钮
.submit-btn {
  margin: $spacer-6 0;
  background: $gradient-primary;
  color: $uni-text-color-inverse;
  font-size: $uni-font-size-lg;
  border-radius: $uni-border-radius-lg;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.disabled {
    opacity: 0.7;
    background: $uni-text-color-grey;
  }
}
</style>
